package com.cskaoyan.controller.wx.lghc;

import com.cskaoyan.config.zjhShiro.MallToken;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.module.bean.AdminInfoBean;
import com.cskaoyan.module.bean.BaseRespVo;


import com.cskaoyan.module.bean.vo.VxLoginVO;
import com.cskaoyan.module.pojo.MarketUser;
import com.cskaoyan.module.pojo.MarketUserExample;
import com.cskaoyan.module.vo.wx.zjh.UserInfoEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author :ligenghuisheng
 * @Description:
 * @Date :2022/4/8  17:29
 */
@RestController
@RequestMapping("wx/auth")
public class VxLoginController {
    @Autowired
    MarketUserMapper userMapper;

    @RequestMapping("login")
    public BaseRespVo login(@RequestBody Map map){
        String username = (String)map.get("username");
        String password = (String)map.get("password");
        VxLoginVO vxLoginVO = new VxLoginVO();

        UserInfoEntity userInfoEntity = new UserInfoEntity();

        Subject subject = SecurityUtils.getSubject();

        try {

            subject.login(new MallToken(username, password,"wechat"));

        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria criteria = marketUserExample.createCriteria();
        criteria.andUsernameEqualTo(username);

        List<MarketUser> marketUsers = userMapper.selectByExample(marketUserExample);

        MarketUser user = marketUsers.get(0);
        vxLoginVO.setToken((String) subject.getSession().getId());
        userInfoEntity.setAvatarUrl(user.getAvatar());
        userInfoEntity.setNickName(username);
        vxLoginVO.setUserInfo(userInfoEntity);



        if (user==null||!password.equals(user.getPassword())) {
            BaseRespVo<Object> baseRespVo = new BaseRespVo<>();
            baseRespVo.setErrno(700);
            baseRespVo.setErrmsg("账号不存在");
            return baseRespVo;
        }else {
            return BaseRespVo.ok(vxLoginVO);
        }
    }

    @PostMapping("logout")
    public BaseRespVo logout() {
        BaseRespVo<Object> baseRespVo = new BaseRespVo<>();
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }
}
